package zy.controller.base;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import zy.controller.BaseController;
import zy.entity.base.shop.T_Base_Shop_Line;
import zy.entity.sys.user.T_Sys_User;
import zy.service.base.shop.ShopLineService;
import zy.util.CommonUtil;
import zy.util.StringUtil;

@Controller
@RequestMapping("base/shopline")
public class ShopLineController extends BaseController{
	@Resource
	private ShopLineService shopLineService;
	
	@RequestMapping("to_shop_line")
	public String to_shop_line(Model model,HttpSession session) {
		T_Sys_User user = getUser(session);
		if (CommonUtil.ONE.equals(user.getShoptype())
				|| CommonUtil.TWO.equals(user.getShoptype())
				|| CommonUtil.FOUR.equals(user.getShoptype())
				|| CommonUtil.FIVE.equals(user.getShoptype())) {// 总公司、分公司、加盟、分公司
			model.addAttribute("shopLine",shopLineService.load(user.getUs_shop_code(), user.getCompanyid()));
		}else{//自营
			model.addAttribute("shopLine",shopLineService.load(user.getShop_upcode(), user.getCompanyid()));
		}
		return "base/shopline/shop_line";
	}
	
	@RequestMapping(value = "save", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
	@ResponseBody
	public String save(T_Base_Shop_Line shopLine, MultipartFile img_logo,HttpSession session) throws IOException, Exception {
		T_Sys_User user = getUser(session);
		if(img_logo != null && StringUtil.isNotEmpty(img_logo.getOriginalFilename())){
			String shop_code;
			if (CommonUtil.ONE.equals(user.getShoptype())
					|| CommonUtil.TWO.equals(user.getShoptype())
					|| CommonUtil.FOUR.equals(user.getShoptype())
					|| CommonUtil.FIVE.equals(user.getShoptype())) {// 总公司、分公司、加盟、分公司
				shop_code = user.getUs_shop_code();
			}else{//自营
				shop_code = user.getShop_upcode();
			}
			String uploadFileName = img_logo.getOriginalFilename();
			String suffix = uploadFileName.substring(uploadFileName.lastIndexOf("."));
			String saveFileName = CommonUtil.SHOP_LOGO_PATH + "/logo_" + user.getCo_code()+"_"+shop_code + suffix;
			File savefile = new File(CommonUtil.CHECK_BASE, saveFileName);
			if (!savefile.getParentFile().exists()) {
				savefile.getParentFile().mkdirs();
			}
			img_logo.transferTo(savefile);
			shopLine.setSpl_logo(saveFileName);
		}
		shopLineService.save(shopLine, getUser(session));
		return JSON.toJSONString(ajaxSuccess(shopLine));
	}
	
}
